package com.jams.goodox.adapter.viewHolder;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.serve.JoinPersonsListActivity;
import com.jams.goodox.adapter.PictureGroupAdapter;
import com.jams.goodox.entity.AnnexBean;
import com.jams.goodox.entity.Neighborhood;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.resp.UserLisResp;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.ImageUtils;
import com.jams.goodox.utils.MessageDialog;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.UserUtils;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.image.ImagePagerActivity;
import com.jams.library.widget.MyGridView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jams on 2016/6/29.
 * ***
 * Tel: ***
 */

public class RentingDetailViewHolder implements View.OnClickListener {
    private Context context;
    private SimpleDraweeView portrait;
    private TextView tvUserName;
    private TextView tvPublishTime;
    public TextView tvLabel;
    private TextView tvContent;
    private MyGridView gvNeighborPicGroup;
    private RecyclerView recyclerView;
    private TextView tvNeighborDetailJoin;
    private RelativeLayout joinGroup;
    private ImageView ivSex;
    private PictureGroupAdapter adapter;
    private RecycleCommonAdapter recycleAdapter;
    private TextView tvCommentCounts;
    private Neighborhood neighborhood;
    private List<AnnexBean> imageList;
    private List<UserLisResp.DataBean.ResultListBean> joinList;
    private TextView tvNoCommentTip;
    private int joinCounts;

    public RentingDetailViewHolder(Context contexts, View view) {
        this.context = contexts;
        imageList = new ArrayList();
        joinList = new ArrayList<>();
        portrait = (SimpleDraweeView) view.findViewById(R.id.sdv_neighbour_user_portrait);
        ivSex = (ImageView) view.findViewById(R.id.iv_sex);
        tvUserName = (TextView) view.findViewById(R.id.tv_innings_name_item);
        tvPublishTime = (TextView) view.findViewById(R.id.tv_innings_time_item);
        tvLabel = (TextView) view.findViewById(R.id.tv_neighbor_label);
        tvContent = (TextView) view.findViewById(R.id.tv_neighbor_content_item);
        gvNeighborPicGroup = (MyGridView) view.findViewById(R.id.gv_neighbor_pic_group);
        joinGroup = (RelativeLayout) view.findViewById(R.id.rl_neighbor_join_group);
        recyclerView = (RecyclerView) view.findViewById(R.id.rcv_neighbor_detail_join);
        tvNeighborDetailJoin = (TextView) view.findViewById(R.id.tv_neighbor_detail_join);
        tvCommentCounts = (TextView) view.findViewById(R.id.tv_neighbor_comment_counts);
        tvNoCommentTip = (TextView) view.findViewById(R.id.tv_no_comment_tip);
        adapter = new PictureGroupAdapter(context, imageList, 54, 9);
        gvNeighborPicGroup.setAdapter(adapter);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(context);
        mLayoutManager.setOrientation(OrientationHelper.HORIZONTAL);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(recycleAdapter = new RecycleCommonAdapter<UserLisResp.DataBean.ResultListBean>(context, joinList, R.layout.only_circle_image) {
            @Override
            public void convert(RecycleCommonViewHolder helper, UserLisResp.DataBean.ResultListBean userInfo, final int position) {
                helper.setSimpleDraweeView(R.id.sdv_only_circle_image_item, StringUtils.newString(userInfo.getUserSimple().getPortraitUrl()));
            }
        });
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    gotoJoinList();
                }
                return true;
            }
        });

        gvNeighborPicGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (imageList.size() == 4 && position == 2) {
                    return;
                }
                List<String> imageListNew = new ArrayList<String>();
                for (int i = 0; i < imageList.size(); i++) {
                    imageListNew.add(imageList.get(i).getUrlPath());
                }
                if (imageListNew.size() == 4 && position > 1) {
                    position--;
                }
                Intent intent = new Intent(context, ImagePagerActivity.class);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, (Serializable) imageListNew);
                context.startActivity(intent);
            }
        });
    }

    //设置数据
    public void setData(Neighborhood neighborhood, UserLisResp.DataBean dataBeen,boolean showUserName) {
        if (neighborhood == null || dataBeen == null) {
            return;
        }
        this.neighborhood = neighborhood;
        this.imageList.clear();
        this.imageList.addAll(neighborhood.getAnnexs());
        portrait.setImageURI(Uri.parse(StringUtils.newString(ImageUtils.getSmallUrl(neighborhood.getUserSimple().getPortraitUrl()))));
        UserUtils.setSexImage(neighborhood.getUserSimple(), ivSex);
        if(showUserName){
            tvUserName.setText(neighborhood.getUserSimple().getUserName());
        }else {
            tvUserName.setText(neighborhood.getUserSimple().getNickName());
        }
        tvPublishTime.setText(neighborhood.getIntime());
        tvLabel.setText(neighborhood.getLabel());
        tvLabel.setVisibility(TextUtils.isEmpty(neighborhood.getLabel()) ? View.GONE : View.VISIBLE);
        tvContent.setText(neighborhood.getTopicContent());
        adapter.notifyDataSetChanged();
        portrait.setOnClickListener(this);
        tvUserName.setOnClickListener(this);
        joinGroup.setOnClickListener(this);
        updateJoinList(dataBeen);
        setJoinData(dataBeen.getPageInfo().getTotal());
    }

    //设置点赞
    private void setJoinData(int counts) {
        joinCounts = counts;
        if (counts == 0) {
            joinGroup.setVisibility(View.GONE);
        } else {
            joinGroup.setVisibility(View.VISIBLE);
        }
        tvNeighborDetailJoin.setText(counts + "人点赞");
    }

    //刷新加入（点赞）人数列表
    public void updateJoinList(UserLisResp.DataBean dataBeen) {
        this.joinList.clear();
        if (dataBeen.getResultList().size() > 5) {
            this.joinList.addAll(dataBeen.getResultList().subList(0, 5));
        } else {
            this.joinList.addAll(dataBeen.getResultList());
        }
        recycleAdapter.notifyDataSetChanged();
        setJoinData(dataBeen.getPageInfo().getTotal());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sdv_neighbour_user_portrait:
            case R.id.tv_innings_name_item:
                if (DataCacheManager.getInstance().isCurrentUser(neighborhood.getUserSimple().getId())) {
                    return;
                }
                String strArray[] = {context.getString(R.string.message_pri_msg)};
                MessageDialog.showBottomMenu(context, strArray, new MessageDialog.MenuDialogOnItemClickListener() {
                    @Override
                    public void onItemClick(int index) {
                        switch (index) {
                            case 1:
                                break;
                        }
                    }
                });
                break;
            case R.id.rl_neighbor_join_group:
                gotoJoinList();
                break;
        }
    }

    //设置评论数量
    public void setCommentCounts(int counts) {
        tvCommentCounts.setText("留言 " + counts);
    }

    //进入加入列表
    private void gotoJoinList() {
        if (neighborhood == null) {
            return;
        }
        Intent intent = new Intent(context, JoinPersonsListActivity.class);
        intent.putExtra("CircleItemBean", neighborhood);
        context.startActivity(intent);
    }

    //设置是否有评论
    public void setCommentTipStatus(boolean visible) {
        if (visible) {
            tvNoCommentTip.setVisibility(View.VISIBLE);
            setCommentCounts(0);
        } else {
            tvNoCommentTip.setVisibility(View.GONE);
        }
    }

    /**
     * 本人点赞成功本地添加一个数据
     *
     * @param bool true的话就是点赞
     */
    public void praise(boolean bool) {
        if (bool) {
            UserLisResp.DataBean.ResultListBean resultListBean = new UserLisResp.DataBean.ResultListBean();
            User user = DataCacheManager.getInstance().getUser();
            user.setId(user.getUserId());
            resultListBean.setUserSimple(user);
            List<UserLisResp.DataBean.ResultListBean> newJoinLList = new ArrayList<>();
            newJoinLList.add(resultListBean);
            if (newJoinLList.size() > 5) {
                joinList.addAll(newJoinLList.subList(0, 5));
            } else {
                joinList.addAll(newJoinLList);
            }
            recycleAdapter.notifyDataSetChanged();
            joinCounts++;
            setJoinData(joinCounts);
        } else {
            for (int i = 0; i < joinList.size(); i++) {
                if (isMyself(joinList.get(i).getUserSimple().getId())) {
                    joinList.remove(i);
                    joinCounts--;
                    setJoinData(joinCounts);
                    recycleAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    private boolean isMyself(String id) {
        if (id == null) {
            return false;
        } else if (id.equals(SePref.getUserId())) {
            return true;
        }
        return false;
    }
}
